/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.icee.myth.gm.api;

/**
 *
 * @author yangyi
 */
/*
 * Copyright 2008 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.IOException;
import java.net.URISyntaxException;

import net.oauth.client.httpclient4.HttpClient4;
import net.oauth.client.OAuthClient;
import net.oauth.OAuthServiceProvider;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthAccessor;
import net.oauth.OAuth;
import net.oauth.OAuthMessage;
import net.oauth.OAuthException;

// See the readme.txt and manpage.txt for more information
public class OAuthHelper {

    String consumerKey;
    String callbackUrl = null;
    String consumerSecret;
    String reqUrl;
    String authzUrl;
    String accessUrl;
    String tokenSecret;

    public OAuthHelper(String consumerKey,
        String callbackUrl,
        String consumerSecret,
        String tokenSecret,
        String reqUrl,
        String authzUrl,
        String accessUrl){
        this.consumerKey = consumerKey;
        this.callbackUrl = callbackUrl;
        this.consumerSecret = consumerSecret;
        this.tokenSecret = tokenSecret;
        this.reqUrl = reqUrl;
        this.authzUrl = authzUrl;
        this.accessUrl = accessUrl;
    }

    private OAuthAccessor createOAuthAccessor() {

        OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl);
        OAuthConsumer consumer = new OAuthConsumer(callbackUrl, consumerKey,
                consumerSecret, provider);
        return new OAuthAccessor(consumer);
    }

    public OAuthMessage sendRequest(Map map, String url) throws IOException,
            URISyntaxException, OAuthException {
        List<Map.Entry> params = new ArrayList<Map.Entry>();
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry p = (Map.Entry) it.next();
            params.add(new OAuth.Parameter((String) p.getKey(),
                    (String) p.getValue()));
        }
        OAuthAccessor accessor = createOAuthAccessor();
        accessor.tokenSecret = tokenSecret;
        OAuthClient client = new OAuthClient(new HttpClient4());
        return client.invoke(accessor, "GET", url, params);
    }
}
